import os
import re
import base64
import time
import datetime
import json
from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for, send_from_directory, current_app, jsonify
)
from sqlalchemy import desc
from jinja2.filters import do_striptags
from werkzeug.utils import secure_filename
from garden import db
from garden.models import Topic,TopicReply, User 
from garden.auth import login_required



ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

bp = Blueprint('topic', __name__)

@bp.route('/')
@bp.route('/topics')
@bp.route('/topics/<int:page>')
def listTopics(page=1):
	# topics = Topic.query.order_by('-pub_time').filter("del_flag = 0").all()
	if g.user == None:
		g.user = User.query.get(1000)

	paginate = Topic.query.order_by(desc('category')).order_by(desc('pub_time')).filter_by(cmnt_id = g.user.cmnt_id).filter_by(del_flag = 0).paginate(page,5,False)
	return render_template('topic/topics.html',topics=paginate.items)

@bp.route('/loadTopics/<int:page>')
def loadTopics(page):
	# topics = Topic.query.order_by('-pub_time').filter("del_flag = 0").all()
	if g.user == None:
		g.user = User.query.get(1000)
		
	paginate = Topic.query.order_by(desc('category')).order_by(desc('pub_time')).filter_by(cmnt_id = g.user.cmnt_id).filter_by(del_flag = 0).paginate(page,5,False)
	topics=paginate.items
	topicList = []
	if topics:
		for topic in topics:
			topicList.append({'id':topic.id,'category':topic.category,'title':topic.title,'content':do_striptags(topic.content),'pub_time':topic.pub_time.strftime('%Y-%m-%d %H:%M:%S')
				,'nickname':topic.user.nickname })

	return jsonify({"topics":topicList})

@bp.route('/newTopic')
@login_required
def newTopic():
	return render_template('topic/post.html')


def allowed_file(filename):
	return '.' in filename and \
		filename.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS


@bp.route('/upload', methods=['GET', 'POST'])
@login_required
def upload_file():
	if request.method == 'POST':

		imgData = request.form['filed']
		if imgData:
			reobj = re.compile('^data:image\/\w+;base64,')
			imgExtension = imgData[imgData.find("/")+1:imgData.find(";")]
			print(imgExtension)
			if imgExtension.lower() in ALLOWED_EXTENSIONS:
				base64Data = reobj.sub("", imgData)
				imagedata = base64.b64decode(base64Data)
				filename = "%s.%s" % (int(round(time.time()*1000)),imgExtension)
				file = open(os.path.join(current_app.config['UPLOAD_FOLDER'],filename),"wb")
				file.write(imagedata)
				file.close()
				# result = {}
				# result['path'] = '/uploads/%s' % filename
				return  jsonify({"path":'/uploads/%s' % filename})

	return ''
@bp.route('/uploads/<filename>')
def uploaded_file(filename):
  return send_from_directory(current_app.config['UPLOAD_FOLDER'],filename)

@bp.route('/pubTopic',methods=['POST'])
@login_required
def pub_topic():
	title = request.form['title']
	content = request.form['content']

	if title and content :
		topic = Topic(title=title,content=content,category='00',tags=None,publisher=g.user.id,pub_time=datetime.datetime.now(),cmnt_id=g.user.cmnt_id)
		db.session.add(topic)
		db.session.commit()
	return render_template('topic/msg.html')

@bp.route('/showTopic/<int:tpc_id>')
def show_topic(tpc_id):
	topic = Topic.query.get(tpc_id)
	# print(topic.replies)
	if topic:
		return render_template('topic/topic.html',topic=topic)
	else:
		return render_template('error.html')

@bp.route('/postTopicReply',methods=['POST'])
@login_required
def post_reply():
	data = request.get_data()
	json_data = json.loads(data.decode("utf-8"))

	reply = TopicReply(content=json_data.get('content'),tpc_id=json_data.get('tpcId'), publisher=g.user.id, pub_time=datetime.datetime.now())
	db.session.add(reply)
	db.session.commit()
	replies = TopicReply.query.filter_by(tpc_id=json_data.get('tpcId'))
	replyList = []
	for reply in replies:
		u = reply.user
		r = {'id':reply.id,'content':reply.content,'publisher':reply.publisher,'pub_time':reply.pub_time.strftime('%Y-%m-%d %H:%M:%S'),'user':{'nickname':u.nickname,'avatar':u.avatar}}
		replyList.append(r)

	return jsonify({"replies":replyList})